
function OrgController(){
    var orgControllerThis = this;
    
	var disable = function(){
		$("#org_message_id").hide();
		$("#org_message_id").empty();
  	  	$(".orgvault_org_button").attr('disabled', 'disabled');
  	    $('#org_form_id :input').attr('readonly','readonly');
        $('#org_persons_list :input').attr('disabled', 'disabled');
  	    $(".orgvault_org_persons_button").attr('disabled', 'disabled');
	    $("#org_throbber").show();
	    //$(".org_message").hide();
  	}
	var enable = function(){
  	    $('#org_form_id :input').removeAttr('readonly');
  	    $(".orgvault_org_button").removeAttr('disabled');
        $(".orgvault_org_persons_button").removeAttr('disabled');
        $('#org_persons_list :input').removeAttr('disabled');
	    $("#org_throbber").hide();  
	}
	var addSelectedOrgPersons = function(selectionDialog, that){
	    console.log("addSelectedOrgPersons");	    
	    var $checked = $("#org_add_persons_list input[name='person_id']:checked");
        var personIds = [];
        $checked.each(function(index) {
            personIds.push({
                "name" : "id",
                "value" : $(this).val()
            });
            console.log("push personId: " + $(this).val());
        });
        console.log("personIds.size: " + personIds.length);
        if(personIds.length == 0){
            $(selectionDialog).dialog("close"); 
            return;
        }
        var orgId = $("#org_add_persons_list").attr("orgId");
        var data = $.param(personIds) + "&orgId=" + orgId;
        console.log("data: " + data);
        var options = {
                
            'success' : function() {
                    $(selectionDialog).dialog("close"); 
                    console.log("will get: " + orgId);
                    that.get(orgId);
                },
            
            'type' : "POST",
            'data' : $.param(personIds) + "&orgId=" + orgId
            
        };
        new AjaxHelper(options).getJSON("/orgPersonPutInsert.app");
	}
	
	var orgPersonsList;
	
	$(document).bind('orgsDisable', function(e) {
		disable();
    });
	
	$(document).bind('orgsEnable', function(e) {
		enable();
	});
	
    if(typeof OrgController.prototype.get == "undefined"){
  
	    OrgController.prototype.get = function(id){
	        console.log("oc get org id: " + id);
	    	disable();
	    	var dfd = $.Deferred(); // this one gets returned	       
        	var options = {
		          'data' : {'id' : id},
        	};
        	var jqXHR_getOrg = new AjaxHelper(options).getJSON("/orgGetOne.app");
		    var jqXHR_getTemplate = {};
	        if(typeof $.template["compiled_org_template"] == "undefined"){
	        	jqXHR_getTemplate = $.get('/template/org.html', function(templateData) {
	                  $.template("compiled_org_template", templateData );
	            });
	        }

            var jqXHR_getOrgPersonsGridActionBarTemplate = {};
            if (typeof $.template["compiled_org_persons_grid_action_bar_template"] == "undefined") {
                jqXHR_getOrgPersonsGridActionBarTemplate = 
                    $.get('/template/org_persons_grid_action_bar.html', function(templateData) {
                        $.template("compiled_org_persons_grid_action_bar_template", templateData);
                    });
            }
	        var deferred = $.when( jqXHR_getOrg, jqXHR_getTemplate, jqXHR_getOrgPersonsGridActionBarTemplate)
              	.then(function(jqXHR_getOrg, jqXHR_getTemplate){
              		// jqXHR_getOrg is an array in this case
              		// index 0 = data
              		// index 1 = text status string
              		// index 2 = jxXHR object
              		if(jqXHR_getOrg[0].error_message && jqXHR_getOrg[0].error_message.name){
              			switch ( jqXHR_getOrg[0].error_message.name ){
              			case "unknown_entity":
              			    console.log("have unknown entity error");
              				$("#org_unknown_entity_error_message_container").show();
              				$("#org_form_id").hide();
              				$("#org_persons_list").hide();
              				break;
              			default :
              				throw "unknown error_message value: " + jqXHR_getOrg[0].error_message;
              			}
              		}else{
	            	  	orgControllerThis.loadForm(jqXHR_getOrg[0].org);
              		}
            	  	enable();
    		        dfd.resolve();
              });
	        return dfd.promise();
	    }

		  OrgController.prototype.loadForm = function(org){
		      var that = this;
		      $("#org_container_id").empty();
		      // Use the org to fill out the template
              $.tmpl("compiled_org_template", org).appendTo( "#org_container_id" );
              // link the form to the org variable, so orgControllerThis changes
              // in the form automatically update the variable.
              $("#org_form_id").link(org);
              
              // set up the persons grid
              
              orgPersonsList = $('#org_persons_list').dataTable(
                  {"aoColumnDefs" : [ 
                                      {"sWidth" : "15px", "aTargets" : [ 0 ]}, 
                                      {"bSortable" : false, "aTargets" : [ 0]}
                                     ],
                  "aaSorting": [[1,'asc']], // make column 2 the default sort colum, asc
                  "sDom" : '<"persons_grid_action_bar"f>t<"org_persons_list_footer"ilp>'
              });
              
              $.tmpl("compiled_org_persons_grid_action_bar_template").prependTo(".persons_grid_action_bar");

              $('#org_person_deletion_checkbox_all_id').click(function() {
                  console.log('click on deletion checkbox.');
                  console.log('checked: ' + this.checked);
                  if (this.checked) {
                      $("#org_persons_list input[name='org_person_id_to_delete']").attr('checked', true);
                  } else {
                      $("#org_persons_list input[name='org_person_id_to_delete']").attr('checked', false);
                  }
              });
              

              $('#org_person_delete_button_id').click(function() {
                  console.log("org person delete");
                  that.orgPersonDelete(org.id);
              });
              
              $('#org_person_add_button_id').click(function() {
                  that.orgPersonAdd(org.id);
              });

              $('.fap_input').keydown(function() {
                    $("#org_save_button_id").text("Save");
                    $("#org_reset_button_id").show();
  	                $('#org_save_button_id').removeAttr('disabled');
              });
              $('#org_name_id').keyup(function() {
            	  $(document).trigger('orgsTreeController.nodeTitleChange', $('#org_name_id').val());
              });
              $("#org_form_id").submit(function(eventObject){
            	  return orgControllerThis.orgSubmitHandler();
              });
              var validator = $("#org_form_id").validate();

              $("#org_reset_button_id").click(function(){
            	  document.getElementById("org_form_id").reset();
            	  var dataArray = [];
            	  dataArray[0] = $('#org_name_id').val();
            	  dataArray[1] = $('#org_id').val();
            	  $(document).trigger('orgsTreeController.nodeTitleChange', dataArray);
                  $("#org_reset_button_id").hide();
          		  $("#org_message_id").empty();
          		  $(".org_message").hide();
                  $("#org_save_button_id").text("Saved");
                  validator.resetForm();
                  $("#org_name_id").focus();
              });
              // use the textlimit plugin to show the number of remaining chars
              $("#org_desc_id").textlimit('#desc_counter_id',200);
              
              $('#org_desc_id').focus(function() {
            	  $("#desc_counter_id").show();
              });
              $('#org_desc_id').blur(function() {
            	  $("#desc_counter_id").hide();
              });
              $('#org_form_id').blur(function() {
            	  console.log("blur called for the form");
              });
              $("#org_container_id").show();
              $("#org_name_id").focus(); // this has no effect if the modal Ajax throbber is running
		  }
    
		  OrgController.prototype.orgSubmitHandler = function(){
		      try{
		          if(!$("#org_form_id").valid()){
		              console.log("organizationSubmitHandler... form has errors, will return with no action");
		              return false;
		          }
          	  	  disable();
		          var options = {
		              'type' : "POST",
		              'data' : $("#org_form_id").serialize()
		          };
		          new AjaxHelper(options).getJSON("/orgPutUpdate.app").then(function(jqXHRdAta){
		        	  // this jqXHR is NOT an array... is the data object
		        	  if(jqXHRdAta.error_message && jqXHRdAta.error_message.name){
			        	  switch ( jqXHRdAta.error_message.name ){
			 		  	  case "duplicate_field":
			 		  		  var message = " Duplicate value on: " + jqXHRdAta.error_message.fieldName;
			 		  		  $("#org_message_icon_error").show();
				 			  $("#org_message_id").text(message).show();
			 		  		  break;
			 		  	  case "unknown_entity":
			 		  		  // How would this happen?
			 		  		  // The org may have been deleted before the submit.
					 		  $("#org_unknown_entity_error_message_container").show();
					 		  $("#org_form_id").hide();
                              $("#org_persons_list").hide();
			 		  		  break;
			 		  	  case "version_conflict" :
					 		  $("#org_version_error_message_container").show();
					 		  $("#org_form_id").hide();
                              $("#org_persons_list").hide();
			 		  		   break;
			 		  	  default :
			 		  		  throw "unknown error_message value: " + jqXHRdAta.error_message;
			        	  }
		        	  }else{
		        		  $(document).trigger('orgsTreeController.nodeDataChange', [jqXHRdAta.org.name, jqXHRdAta.org.id, jqXHRdAta.org.version]);
				    	  orgControllerThis.loadForm(jqXHRdAta.org);
		        	  }
	            	  enable();
			      });
		      }catch(exception){
		          console.error(exception);
		      }
		      return false;
		  }
		  /**
		   * Opens the person add selection dialog.
		   */
		  OrgController.prototype.orgPersonAdd = function(orgId) {
	            var that = this;	            
	              console.log("orgPersonAdd orgId: " + orgId);
	              $( "#org_person_selection_dialog" ).dialog({
	                  height: 500,
	                  width: 800,
	                  autoOpen: false,
	                  modal: true,
	                  resizable: true,
	                  buttons: { "Ok": function() { 
	                                  addSelectedOrgPersons(this, that);
	                              },
	                             "Cancel": function() { 
	                                  $(this).dialog("close"); 
	                              }
	                  }, 
	                  title: "Select people"
	              });
	            
	            // open modal dialog to select people
	            $( "#org_person_selection_dialog").dialog("open");
	            var that = this;	            
	            var jqXHR = new AjaxHelper().getJSON("/personGetList.app?orgId=" + orgId);
	            var jqXHR_getTemplate = {};
	            if (typeof $.template["compiled_org_persons_add_template"] == "undefined") {
	                jqXHR_getTemplate = $.get('/template/personsToAddToOrg.html', function(templateData) {
	                    $.template("compiled_org_persons_add_template", templateData);
	                });
	            }
	            
	            $.when(jqXHR, jqXHR_getTemplate).then(function() {
	                console.log("when!");
	                $("#org_person_selection_dialog").empty();
	                $.tmpl("compiled_org_persons_add_template",
	                        $.parseJSON(jqXHR.responseText)).appendTo("#org_person_selection_dialog");
	                
	                var orgPersonsAddList = $('#org_add_persons_list').dataTable(
	                    {"aoColumnDefs" : [ 
	                                        {"sWidth" : "15px", "aTargets" : [0]}, 
	                                        {"bSortable" : false, "aTargets" : [0]}
	                                       ],
	                    "aaSorting": [[1,'asc']],
	                    "sDom" : '<f>t<ilp>'
	                });

	                $('#org_person_add_checkbox_id').click(function() {
	                    if (this.checked) {
	                        $("#org_add_persons_list input[name='person_id']").attr('checked', true);
	                    } else {
	                        $("#org_add_persons_list input[name='person_id']").attr('checked', false);
	                    }
	                });
	            });
	        }

        OrgController.prototype.orgPersonDelete = function(orgId) {
            var that = this;
            console.log('org person delete');
            var $checked = $("#org_persons_list input[name='org_person_id_to_delete']:checked");
            var deletionIds = [];
            $checked.each(function(index) {
                deletionIds.push({
                    "name" : "id",
                    "value" : $(this).val()
                });
                console.log("org person id to be deleted: " + $(this).val());
            });

            if (deletionIds.length == 0) {
                alert("Please select one or more persons to be deleted.");
                return;
            } else {
                if (!confirm("Confirm deletions?")) {
                    return;
                }
            }

            var options = {
                'success' : function() {
                    $(document).trigger('personsEnable');
                    if (deletionIds.length == 1) {
                        // remove the row
                        console.log("deletionIds[0].value: " + deletionIds[0].value);
                        var checkboxArray = $("#org_persons_list .orgvault_org_person_deletion_checkbox[value='" + deletionIds[0].value + "']");
                        var tr = $(checkboxArray[0]).parent().parent()[0];
                        orgPersonsList.fnDeleteRow(tr);
                        $(document).trigger('orgsEnable');
                    }else{
                        $(document).trigger('orgsEnable');
                        that.get(orgId);
                    }
                },
                'type' : "POST",
                'data' : $.param(deletionIds)
            };
            $(document).trigger('orgsDisable');
            new AjaxHelper(options).getJSON("/orgPersonDelete.app");
        }
		  
    }
}